<?php

namespace app\admin\service;

use app\model\PayRecord;
use app\model\User;
use app\common\Common;
use app\common\Error;
use think\facade\Cache;
use app\model\Applet;
use app\model\Client;
use think\facade\Db;
use think\facade\Queue;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use app\model\VideoDetails;
use app\model\Videos;
use app\model\VideoWechatTarget;
use app\model\WechatAudit;
use app\model\WechatCatalog;
use SimpleXMLElement;

class WechatTargetService
{
    private $model;
    private $appletModel;
    private $clientModel;
    public $videoModel;
    public $wechatTargetModel;
    public $wechatAuditModel;
    public $wechatCatalogModel;
    public function __construct(User $model, Applet $appletModel, Client $clientModel, Videos $videoModel, VideoWechatTarget $wechatTargetModel, WechatAudit $wechatAuditModel, WechatCatalog $wechatCatalogModel)
    {
        $this->model = $model;
        $this->appletModel = $appletModel;
        $this->clientModel = $clientModel;
        $this->videoModel = $videoModel;
        $this->wechatTargetModel = $wechatTargetModel;
        $this->wechatAuditModel = $wechatAuditModel;
        $this->wechatCatalogModel = $wechatCatalogModel;
    }

    //送审商品列表
    public function targetList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $where = [];
        // $where[] = ['status', '=', 1];
        if (!empty($params['name'])) {
            $where[] = ['product_name', 'like', '%' . $params['name'] . '%'];
        }

        $data = $this->wechatTargetModel->getPagingDataByWhere($where, $page, $limit, '*');
        return $data;
    }
    //审核列表
    public function auditList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $where = [];
        // $where[] = ['status', '=', 1];
        if (!empty($params['name'])) {
            $where[] = ['catalog_name', 'like', '%' . $params['name'] . '%'];
        }
        if (!empty($params['product_id'])) {
            $where[] = ['product_id', 'like', '%' . $params['product_id'] . '%'];
        }
        $data = $this->wechatAuditModel->getPagingDataByWhere($where, $page, $limit, '*');
        return $data;
    }
    //商品库列表
    public function catalogList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $where = [];
        // $where[] = ['status', '=', 1];
        if (!empty($params['name'])) {
            $where[] = ['catalog_name', 'like', '%' . $params['name'] . '%'];
        }
        if (!empty($params['adv_id'])) {
            $where[] = ['adv_id','=',  $params['adv_id']];
        }
        $data = $this->wechatCatalogModel->getPagingDataByWhere($where, $page, $limit, '*');
        return $data;
    }

    // 获取短剧下拉列表
    public function getVideoSelectList($params)
    {
        $where = [
            ['is_delete', '=', 0], ['is_copy', '=', 0], ['original_id','=', 0]
        ];
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        $data = $this->videoModel->getDataByWhere($where, 'id, name');

        return $data;
    }
    // 获取小程序列表
    public function getAppletSelectList($params)
    {
        $where = [
            ['status', '=',1]
        ];
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        $data = $this->appletModel->getDataByWhere($where, 'id, name');

        return $data;
    }
    // 获取小程序列表
    public function getCatalogSelectList($params)
    {
        $where = [
            ['status', '=',1]
        ];
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        $data = $this->wechatCatalogModel->getDataByWhere($where, 'id,adv_id,catalog_id,catalog_name');
        foreach($data as $key => $val) {
            $data[$key]['name'] = $val['adv_id'] . '-' . $val['catalog_id'] . '-' . $val['catalog_name'];
        }
        return $data;
    }
    // 添加/编辑视频商品
    public function editWechatTarget($params, $userInfo)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }
        $cargory = $this->cargoryList($params);
        $params['second_category_id'] = $cargory['second_category_id'];
        $params['second_category_name'] = $cargory['second_category_name'];
        $params['third_category_id'] = $cargory['third_category_id'];
        $params['third_category_name'] = $cargory['third_category_name'];
        $params['first_category_id'] = $params['sex_cargory'];
        if($params['sex_cargory'] == 185437) {
            $params['first_category_name'] = '男频';
        } else {
            $params['first_category_name'] = '女频';
        }
        $params['expiration_time'] = strtotime($params['expiration_time']);
        // $params['admin_user_id'] = Session::get('user_id');
        $params['admin_user_id'] = $userInfo['user_id'];
        if($params['is_audit'] == 0) {
            $params['audit_status'] = 0;
        }
        if($params['applet_id']) {
            $applet = $this->appletModel->getInfoById($params['applet_id'], 'origin_id');
            $params['target_url_mini_program_id'] = $applet['origin_id'];
        }
        $id = $this->wechatTargetModel->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }

    //查询详情
    public function detail($params)
    {
        $list = $this->wechatTargetModel->getInfoById($params['id'], '*');
        return $list;
    }
    //查询商品库详情
    public function detailCatalog($params)
    {
        $list = $this->wechatCatalogModel->getInfoById($params['id'], '*');
        return $list;
    }
    //分类列表
    //地址 https://docs.qq.com/doc/DVUN6RXpjQ0liUGl1
    public function cargoryList($params)
    {
        $arr = [
            ["name" => "都市逆袭","id" => 185439,
            'children' => [
                ["name" => "豪门赘婿儿媳","id" => 185467],
                ["name" => "职场社畜","id" => 185468],
                ["name" => "异能奇遇","id" => 185469],
            ]],
            ["name" => "都市爱情","id" => 185440,
            'children' => [
                ["name" => "麻雀变凤凰","id" => 185470],
                ["name" => "都市灰姑娘","id" => 185471],
                ["name" => "破镜重圆","id" => 185472],
                ["name" => "总裁追爱","id" => 185473],
                ["name" => "三教九流","id" => 185474],
                ["name" => "契约爱情","id" => 185475],
            ]],
            ["name" => "都市热血","id" => 185441,
            'children' => [
                ["name" => "总裁除恶","id" => 185476],
                ["name" => "战神归来","id" => 185477],
                ["name" => "守护家人","id" => 185478],
                ["name" => "东山再起","id" => 185479],
            ]],
            ["name" => "都市家庭","id" => 185442,
            'children' => [
                ["name" => "世道人伦","id" => 185480],
                ["name" => "生活喜剧","id" => 185481],
            ]],
            ["name" => "都市复仇","id" => 185443,
            'children' => [
                ["name" => "家庭伦理","id" => 185482],
                ["name" => "商海谍战","id" => 185483],
                ["name" => "江湖帮派","id" => 185484],
            ]],
            ["name" => "乡村生活","id" => 185444,
            'children' => [
                ["name" => "乡村喜剧","id" => 185485],
                ["name" => "乡村文艺","id" => 185486],
            ]],
            ["name" => "校园生活","id" => 185445,
            'children' => [
                ["name" => "懵懂纯爱","id" => 185487],
                ["name" => "成长奋斗","id" => 185488],
            ]],
            ["name" => "年代","id" => 185446,
            'children' => [
                ["name" => "民国爱情","id" => 185489],
                ["name" => "战争谍报","id" => 185490],
                ["name" => "家宅传承","id" => 185491],
                ["name" => "军阀乱世","id" => 185492],
            ]],
            ["name" => "古风","id" => 185447,
            'children' => [
                ["name" => "正史传记","id" => 185493],
                ["name" => "传奇演义","id" => 185494],
                ["name" => "王朝架空","id" => 185495],
                ["name" => "门阀宅斗","id" => 185496],
                ["name" => "浪漫爱情","id" => 185497],
            ]],
            ["name" => "仙侠","id" => 185448,
            'children' => [
                ["name" => "修仙","id" => 185498],
                ["name" => "武侠","id" => 185499],
            ]],
            ["name" => "魔幻","id" => 185449,
            'children' => [
                ["name" => "西方魔幻","id" => 185500],
                ["name" => "东方魔幻","id" => 185501],
                ["name" => "重生转世","id" => 185502],
                ["name" => "穿越（书传/反穿/快穿）","id" => 185503],
            ]],
            ["name" => "科幻","id" => 185450,
            'children' => [
                ["name" => "系统流","id" => 185504],
                ["name" => "空间流","id" => 185505],
                ["name" => "末世流","id" => 185506],
                ["name" => "灾难流","id" => 185507],
                ["name" => "星际流","id" => 185508],
                ["name" => "机甲流","id" => 185509],
            ]],
            ["name" => "灵异","id" => 185451,
            'children' => [
                ["name" => "野村志怪","id" => 185510],
                ["name" => "探险生存","id" => 185511],
            ]],
            ["name" => "悬疑犯罪","id" => 185452,
            'children' => [
                ["name" => "诡秘悬疑","id" => 185512],
                ["name" => "推理探案","id" => 185513],
            ]],
        ];
        if(!empty($params['category_id'])) {
            $list = [];
            for($i = 0;$i < count($arr);$i++) {
                $m_arr = $arr[$i]['children'];
                for($j = 0;$j < count($m_arr);$j++) {
                    if($m_arr[$j]['id'] == $params['category_id']) {
                        $list['second_category_id'] = $arr[$i]['id'];
                        $list['second_category_name'] = $arr[$i]['name'];
                        $list['third_category_id'] = $m_arr[$j]['id'];
                        $list['third_category_name'] = $m_arr[$j]['name'];
                    }
                }
            }
            return $list;
        }
        return $arr;
    }
    // 添加/编辑商品库
    public function editCatalog($params, $userInfo)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }
        $catalog = $this->wechataddCatalog($params);

        $id = $this->wechatCatalogModel->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }
    /**
    * 腾讯广告添加商品库
    *
    * @param [type] $params
    * @return void
    *地址：https://developers.e.qq.com/docs/apilist/business_assets/product_catalog
    */
    public function wechataddCatalog($params)
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $token = Common::getTencentAdDeveloperAppAccessToken($params['wx_type']);
        $url = 'https://api.e.qq.com/v1.1/product_catalogs/add';
        $commonParameters = [
            'access_token' => $token,
            'timestamp' => time(),
            'nonce' => md5(uniqid('', true))
        ];
        $catalog_scale_type = $params['catalog_scale_type'] == 1 ? 'CATALOG_SCALE_TYPE_HUGE' : 'CATALOG_SCALE_TYPE_NORMAL';
        $catalog_type = $params['catalog_type'] == 0 ? 'CATALOG_TYPE_STANDARD ' : 'CATALOG_TYPE_STANDARD';
        $industry_type = $params['industry_type'] == 0 ? 'VERTICAL_WE_MEDIA' : 'VERTICAL_WE_MEDIA';
        $parameters = [
            'account_id' => $params['adv_id'],
            'catalog_name' => $params['catalog_name'],
            'catalog_scale_type' => $catalog_scale_type,
            'catalog_type' => $catalog_type,
            'industry_type' => $industry_type
        ];
        $requestUrl = $url . '?' . http_build_query($commonParameters);
        $response = Common::curlPostRequest($requestUrl, $parameters);
        $costData = json_decode($response, true);
        return $costData;
    }
    /**
     * 腾讯广告拉取商品库
     *
     * @param [type] $params['account_id']  广告主id
     * @return void
     * 地址：https://developers.e.qq.com/docs/apilist/business_assets/product_catalog
     */
    public function pullingCatalog($params)
    {
        if(empty($params['wx_type'])){
            return [];
        }
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
 
        $token = Common::getTencentAdDeveloperAppAccessToken($params['wx_type']);
        $url = 'https://api.e.qq.com/v1.1/product_catalogs/get';
        $commonParameters = [
            'access_token' => $token,
            'timestamp' => time(),
            'nonce' => md5(uniqid('', true)),
            'fields' => ['product_catalog_id','product_catalog_name','product_catalog_type','product_catalog_vertical','product_catalog_status']
        ];
        $parameters = [
            'account_id' => $params['account_id'],
            'page' => 1,
            'page_size' => 300
        ];

        $parameters = array_merge($commonParameters, $parameters);

        foreach ($parameters as $key => $item) {
            if (!is_string($item)) {
                $parameters[$key] = json_encode($item);
            }
        }

        $requestUrl = $url . '?' . http_build_query($parameters);

        $response = Common::curlRequest($requestUrl);
        $costData = json_decode($response, true);
        if($costData['code'] == 0) {
            $arr = [];
            //获取总数
            $total_number = $costData['data']['page_info']['total_number'];
            $list = $costData['data']['list'];
            $product_catalog_status = [
                'PRODUCT_CATALOG_STATUS_PREPARE' => 0,
                'PRODUCT_CATALOG_STATUS_NORMAL' => 1,
                'PRODUCT_CATALOG_STATUS_SUSPEND' => 2,
                'PRODUCT_CATALOG_STATUS_DELETED' => 3
            ];
            for($i = 0;$i < $total_number;$i++) {
                $catalogFind = $this->wechatCatalogModel->getInfoByWhere(['adv_id' => $params['account_id'],'catalog_id' => $list[$i]['product_catalog_id']]);
                if(empty($catalogFind)) {
                    $arr[] = [
                        'adv_id' => $params['account_id'],
                        'catalog_id' => $list[$i]['product_catalog_id'],
                        'catalog_name' => $list[$i]['product_catalog_name'],
                        'catalog_status' => $product_catalog_status[ $list[$i]['product_catalog_status']],
                        'created_at' => time(),
                        'wx_type'=>$params['wx_type']
                    ];
                } else {
                    $this->wechatCatalogModel->where(['id' => $catalogFind['id']])->update([
                        'updated_at' => time(),'catalog_name' => $list[$i]['product_catalog_name'],
                        'catalog_status' => $product_catalog_status[ $list[$i]['product_catalog_status']],
                        'wx_type'=>$params['wx_type']
                    ]);
                }
            }
            if(!empty($arr)) {
                $this->wechatCatalogModel->saveAll($arr);
            }
        }
        return $costData;
    }
    /**
     * 腾讯商品库拉取商品
     *
     * @param [type] $params
     * @return void
     * 地址：https://developers.e.qq.com/docs/apilist/business_assets/product_catalog
     */
    public function catalogTarget($params)
    {
        $catalogFind = $this->wechatCatalogModel->getInfoById($params['id'], '*');
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $token = Common::getTencentAdDeveloperAppAccessToken($catalogFind['wx_type']);
        $url = 'https://api.e.qq.com/v1.1/product_items/get';
        $commonParameters = [
            'access_token' => $token,
            'timestamp' => time(),
            'nonce' => md5(uniqid('', true)),
            'fields' => ['product_outer_id','product_name','product_image_url','first_category_name','second_category_name','third_category_name','description','product_select_score','data_source','is_video']
        ];
        $parameters = [
            'account_id' => $catalogFind['adv_id'],
            'product_catalog_id' => $catalogFind['catalog_id'],
        ];
        if(!empty($params['name'])) {
            $parameters['filtering'][] = [
                'field' => 'product_name',
                'operator' => 'EQUALS',
                'values' => [$params['name']]
            ];
        }
        if(!empty($params['target_id'])) {
            $parameters['filtering'][] = [
                'field' => 'product_outer_id',
                'operator' => 'EQUALS',
                'values' => [$params['target_id']]
            ];
        }
        $parameters = array_merge($commonParameters, $parameters);
        foreach ($parameters as $key => $item) {
            if (!is_string($item)) {
                $parameters[$key] = json_encode($item);
            }
        }
        $requestUrl = $url . '?' . http_build_query($parameters);
        $response = Common::curlRequest($requestUrl);
        $costData = json_decode($response, true);
        if($costData['code'] == 0) {
            return ['data' => $costData['data']['list'],'total' => count($costData['data']['list'])] ;
        } else {
            return [];
        }

    }
    /**
     * 腾讯的审核状态
     *
     * @param [type] $params
     * @return void
     */
    public function examineTarget($params)
    {
        $catalogFind = $this->wechatAuditModel->getInfoById($params['id'], '*');
        if(empty($catalogFind)) {
            return false;
        }
        $wxFind = $this->wechatCatalogModel->getInfoById($params['t_catalog_id'], '*');
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $token = Common::getTencentAdDeveloperAppAccessToken($wxFind['wx_type']);
        $url = 'https://api.e.qq.com/v1.1/products_system_status/get';
        $commonParameters = [
            'access_token' => $token,
            'timestamp' => time(),
            'nonce' => md5(uniqid('', true))
        ];
        $parameters = [
            'account_id' => $catalogFind['adv_id'],
            'product_catalog_id' =>  $catalogFind['catalog_id'],
            'page' => 1,
            'page_size' => 100
        ];

        $parameters2 = array_merge($commonParameters, $parameters);
        $requestUrl = $url . '?' . http_build_query($parameters2);
        // var_dump($requestUrl);
        $response = Common::curlRequest($requestUrl);
        $costData = json_decode($response, true);
        if($costData['code'] == 0) {
            $list=$costData['data']['list'];
            $total_number=$costData['data']['page_info']['total_number'];
            $total_page=$costData['data']['page_info']['total_page'];
            if($total_number==0){
                return $costData;
            }else{
                if($total_page==0){
                    return $costData;
                }
                for($i=1;$i<=$total_page;$i++){
                    $$parameters['page']=$i;
                    $parameters2=array_merge($commonParameters, $parameters);
                    $requestUrl = $url . '?' . http_build_query($parameters2);
                    $response = Common::curlRequest($requestUrl);
                    if($costData['code']==0){
                        $list=array_merge($list,$costData['data']['list']);
                    }
                }
                $audit_status=[
                    'PRODUCT_STATUS_PENDING'=>0,
                    'PRODUCT_STATUS_AUDITING'=>1,
                    'PRODUCT_STATUS_PASS'=>2,
                    'PRODUCT_STATUS_REJECTED'=>3
                ];
                foreach($list as $key=>$val){
                    $arr=[
                        'updated_at'=>time(),
                        'audit_remark'=>$val['reject_message'],
                        'audit_status'=>$audit_status[$val['system_status']]
                    ];
                    $this->wechatAuditModel->where(['product_id'=>$val['product_id']])->update($arr);
                }
            }
        }
        return false;
    }
    //添加商品到腾讯
    public function audit($params)
    {
        $targetFind = $this->wechatTargetModel->getInfoById($params['id'], '*');
        $catalogFind = $this->wechatCatalogModel->getInfoById($params['catalog_id'], '*');
        if(empty($catalogFind) || empty($targetFind)) {
            return false;
        }
        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $token = Common::getTencentAdDeveloperAppAccessToken($catalogFind['wx_type']);
        $url = 'https://api.e.qq.com/v1.1/product_items/add';
        $commonParameters = [
            'access_token' => $token,
            'timestamp' => time(),
            'nonce' => md5(uniqid('', true))
        ];
        $spec_list = [];
        $product_outer_id =  $catalogFind['adv_id'] . $catalogFind['catalog_id'] . $targetFind['id'];
        $spec_list[0]['product_outer_id'] = $product_outer_id;//商品ID
        $spec_list[0]['product_name'] = $targetFind['product_name']; //商品名称

        $expiration_time = date('Y-m-d H:i:s', $targetFind['expiration_time']);
        $spec_list[0]['expiration_time'] = $expiration_time; //商品下架时间
        $created_at = date('Y-m-d H:i:s', $targetFind['created_at']);
        //商品创建时
        $spec_list[0]['created_time'] = $created_at;
        //视频发布时间
        $spec_list[0]['publish_time'] = $created_at;
        if(!empty($targetFind['updated_at'])) {
            $updated_at = date('Y-m-d H:i:s', $targetFind['updated_at']);
            //商品更新时间
            $spec_list[0]['lastmod_time'] = $updated_at;
        }
        //商品主图
        $spec_list[0]['image_url'] = $targetFind['image_url'];
        //商品主视频
        $spec_list[0]['video_url'] = $targetFind['video_url'];
        //商品在线状态
        if(isset($val['product_sale_status'])) {
            $product_sale_status = $targetFind['product_sale_status'] == 1 ? 'PRODUCT_SALE_STATUS_ONLINE' : 'PRODUCT_SALE_STATUS_OFFLINE';
            $spec_list[0]['product_sale_status'] = $product_sale_status;
        }
        //一级分类ID
        $spec_list[0]['first_category_id'] = $targetFind['first_category_id'];
        $spec_list[0]['first_category_name'] = $targetFind['first_category_name'];
        //二级分类ID
        $spec_list[0]['second_category_id'] = $targetFind['second_category_id'];
        $spec_list[0]['second_category_name'] = $targetFind['second_category_name'];
        //三级分类ID
        $spec_list[0]['third_category_id'] = $targetFind['third_category_id'];
        $spec_list[0]['third_category_name'] = $targetFind['third_category_name'];
        //商品描述
        if(!empty($targetFind['description'])) {
            $spec_list[0]['description'] = $targetFind['description'];
        }
        //作者
        $spec_list[0]['author'] = $targetFind['author'];
        //剧集数
        $spec_list[0]['episode_count'] = $targetFind['video_arr']['sylloge'];
        //连载状态
        $serial_status = $targetFind['serial_status'] == 1 ? 'SERIAL_STATUS_FINISH' : 'SERIAL_STATUS_SERIALIZE';
        $spec_list[0]['serial_status'] = $serial_status;
        //付费状态
        $pay_status = $targetFind['pay_status'] == 1 ? 'PAY_STATUS_PAID' : ($targetFind['pay_status'] == 2 ? 'PAY_STATUS_MEMBER' : 'PAY_STATUS_FREE');
        $spec_list[0]['pay_status'] = $pay_status;
        //是否为新剧
        $is_new_play = $targetFind['is_new_play'] == 1 ? '是' : '否';
        $spec_list[0]['is_new_play'] = $is_new_play;
        //内容来源
        $soure_arr = [0 => '网文IP',1 => '漫画',2 => '游戏',3 => '原创',4 => '其他'];
        $content_source = $soure_arr[$targetFind['content_source']];
        $spec_list[0]['content_source'] = $content_source;
        //是否系列剧
        $spec_list[0]['is_series'] = $targetFind['is_series'];
        //系列剧第几部
        $spec_list[0]['episode'] = 0;
        //系列剧商品ID
        $spec_list[0]['series_product_id'] = 0;
        //微信落地页
        $spec_list[0]['wechat_page_url'] = $targetFind['target_url_wechat'];
        //微信小程序ID
        $spec_list[0]['mini_program_id'] = $targetFind['target_url_mini_program_id'];
        //微信小程序路径
        $spec_list[0]['mini_program_path'] = $targetFind['target_url_mini_program_path'];
        $parameters = [
            'account_id' => $catalogFind['adv_id'],//广告id
            'product_catalog_id' =>  $catalogFind['catalog_id'],//商品库id
            'product_item_spec_list' => json_encode($spec_list),
        ];
        $requestUrl = $url . '?' . http_build_query($commonParameters);
        $response = Common::curlPostRequest($requestUrl, $parameters);
        $costData = json_decode($response, true);

        if($costData['code'] == 0) {
            $arr = [
                't_catalog_id' =>  $catalogFind['id'],
                'target_id' => $params['id'],
                'product_id' => $product_outer_id,
                'adv_id' =>  $catalogFind['adv_id'],
                'catalog_id' =>  $catalogFind['catalog_id'],
                'catalog_name' =>  $catalogFind['catalog_name'],
                'audit_status' => 1,

            ];
            $auditfind = $this->wechatAuditModel->getInfoByWhere(['catalog_id' => $catalogFind['catalog_id'],'product_id' => $product_outer_id]);
            if($auditfind) {
                $arr['updated_at'] = time();
                $this->wechatAuditModel->where(['id' => $auditfind['id']])->update($arr);
            } else {
                $arr['created_at'] = time();
                $this->wechatAuditModel->save($arr);
            }

            return true;
        }
        return false;
    }
    /**
     * 腾讯商品定时拉取接口
     *
     * @param [type] $params
     * @return void
     */
    public function taskTarget($params)
    {
        $list = $this->wechatTargetModel->where(['is_audit' => 1,'audit_status' => 0])->select();
        $xml = new SimpleXMLElement('<product_set></product_set>');
        $soure_arr = [0 => '网文IP',1 => '漫画',2 => '游戏',3 => '原创',4 => '其他'];
        foreach($list as $key => $val) {
            $product = $xml->addChild('product');
            //商品ID
            $product->addChild('product_id', "<![CDATA[{$val['id']}]]>");
            //商品名称
            $product->addChild('product_name', "<![CDATA[{$val['product_name']}]]>");
            $expiration_time = date('Y-m-d H:i:s', $val['expiration_time']);
            //商品下架时间
            $product->addChild('expiration_time', "<![CDATA[{$expiration_time}]]>");
            $created_at = date('Y-m-d H:i:s', $val['created_at']);
            //商品创建时间
            $product->addChild('created_time', "<![CDATA[{$created_at}]]>");
            //视频发布时间
            $product->addChild('publish_time', "<![CDATA[{$created_at}]]>");
            if(!empty($val['updated_at'])) {
                $updated_at = date('Y-m-d H:i:s', $val['updated_at']);
                //商品更新时间
                $product->addChild('lastmod_time', "<![CDATA[{$updated_at}]]>");
            }
            //商品主图
            $product->addChild('image_url', "<![CDATA[{$val['image_url']}]]>");
            //商品主视频
            $product->addChild('video_url', "<![CDATA[{$val['video_url']}]]>");
            //商品在线状态
            if(isset($val['product_sale_status'])) {
                $product_sale_status = $val['product_sale_status'] == 1 ? 'PRODUCT_SALE_STATUS_ONLINE' : 'PRODUCT_SALE_STATUS_OFFLINE';
                $product->addChild('product_sale_status', "<![CDATA[{$product_sale_status}]]>");
            }
            //一级分类ID
            $product->addChild('first_category_id', "<![CDATA[{$val['first_category_id']}]]>");
            $product->addChild('first_category_name', "<![CDATA[{$val['first_category_name']}]]>");
            //二级分类ID
            $product->addChild('second_category_id', "<![CDATA[{$val['second_category_id']}]]>");
            $product->addChild('second_category_name', "<![CDATA[{$val['second_category_name']}]]>");
            //三级分类ID
            $product->addChild('third_category_id', "<![CDATA[{$val['third_category_id']}]]>");
            $product->addChild('third_category_name', "<![CDATA[{$val['third_category_name']}]]>");
            //商品描述
            if(!empty($val['description'])) {
                $product->addChild('description', "<![CDATA[{$val['description']}]]>");
            }
            //作者
            $product->addChild('author', "<![CDATA[{$val['author']}]]>");
            //剧集数
            $product->addChild('episode_count', "<![CDATA[{$val['video_arr']['sylloge']}]]>");
            //连载状态
            $serial_status = $val['serial_status'] == 1 ? '完结' : '连载';
            $product->addChild('serial_status', "<![CDATA[{$serial_status}]]>");
            //付费状态
            $pay_status = $val['pay_status'] == 1 ? '付费' : ($val['pay_status'] == 2 ? '会员' : '免费');
            $product->addChild('pay_status', "<![CDATA[{$pay_status}]]>");
            //是否为新剧
            $is_new_play = $val['is_new_play'] == 1 ? '是' : '否';
            $product->addChild('is_new_play', "<![CDATA[{$is_new_play}]]>");
            //内容来源
            $content_source = $soure_arr[$val['content_source']];
            $product->addChild('content_source', "<![CDATA[{$content_source}]]>");
            //是否系列剧
            $product->addChild('is_series', "<![CDATA[{$val['is_series']}]]>");
            //系列剧第几部
            $product->addChild('episode', "<![CDATA[0]]>");
            //系列剧商品ID
            $product->addChild('series_product_id', "<![CDATA[0]]>");
            //微信落地页
            $product->addChild('target_url_wechat', "<![CDATA[{$val['target_url_wechat']}]]>");
            //微信小程序ID
            $product->addChild('target_url_mini_program_id', "<![CDATA[{$val['target_url_mini_program_id']}]]>");
            //微信小程序路径
            $product->addChild('target_url_mini_program_path', "<![CDATA[{$val['target_url_mini_program_path']}]]>");
        }
        $xmlString = $xml->asXML();
        // 将 XML 字符串写入文件
        $file = 'taskTarget.xml';
        file_put_contents($file, $xmlString);
        $xmltwo = new SimpleXMLElement('<sitemapindex></sitemapindex>');
        $producttwo = $xmltwo->addChild('sitemap');
        $producttwo->addChild('loc', 'https://aisaas.mynatapp.cc/' . $file);
        $time = date('Y-m-d H:i:s', time());
        $producttwo->addChild('lastmod', $time);
        return $xmltwo->asXML();
    }
}
